package cn.edu.ncut.cs.springboot.springsecuritydemo.controller;

import cn.edu.ncut.cs.springboot.springsecuritydemo.entity.Permission;
import cn.edu.ncut.cs.springboot.springsecuritydemo.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/permissions")
@PreAuthorize("hasRole('ADMIN')")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    // 查询所有权限
    @GetMapping
    public List<Permission> getAllPermissions() {
        return permissionService.getAllPermissions();
    }

    // 根据 ID 查询权限
    @GetMapping("/{id}")
    public ResponseEntity<Permission> getPermissionById(@PathVariable Long id) {
        Optional<Permission> permission = permissionService.getPermissionById(id);
        return permission.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).build());
    }

    // 创建新的权限
    @PostMapping
    public ResponseEntity<Permission> createPermission(@RequestBody Permission permission) {
        Permission newPermission = permissionService.createPermission(permission);
        return ResponseEntity.status(HttpStatus.CREATED).body(newPermission);
    }

    // 更新权限
    @PutMapping("/{id}")
    public ResponseEntity<Permission> updatePermission(@PathVariable Long id, @RequestBody Permission permission) {
        Permission updatedPermission = permissionService.updatePermission(id, permission);
        return updatedPermission != null ? ResponseEntity.ok(updatedPermission) : ResponseEntity.status(HttpStatus.NOT_FOUND).build();
    }

    // 删除权限
    @DeleteMapping("/{id}")
    public ResponseEntity<Permission> deletePermission(@PathVariable Long id) {
        Optional<Permission> permission = permissionService.getPermissionById(id);
        if (permission.isPresent()) {
            permissionService.deletePermission(id);
            return ResponseEntity.status(HttpStatus.OK).body(permission.get());  // 返回已删除的权限信息
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();  // 如果未找到，返回 404
        }
    }

}
